﻿using Furion;
using Furion.DependencyInjection;
using Furion.LinqBuilder;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using System.Security.Claims;
using XinGuanERP.Db;
using XinGuanERP.Models.Po.system;

namespace XinGuanERP.Attributes.system
{
    public class MyActionFilterAttribute : ActionFilterAttribute, ITransient
    {
        private readonly DefaultDbContext _defaultDbContext;
        public MyActionFilterAttribute(DefaultDbContext defaultDbContext)
        {
            _defaultDbContext = defaultDbContext;
        }

        private SysActionLog sysActionLog = new()
        {
            ActionId = Guid.NewGuid().ToString().Replace("-", "").ToUpper()
        };
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            // 获取请求Host
            sysActionLog.RequestHost = context.HttpContext.Request.Host.ToString();
            // 获取请求方法
            sysActionLog.RequestMethod = context.HttpContext.Request.Method;
            // 获取请求Url
            sysActionLog.RequestPath = context.HttpContext.Request.Path.ToString();

            var descriptor = context.ActionDescriptor as ControllerActionDescriptor;
            string param = string.Empty;
            string globalParam = string.Empty;

            var jsonSetting = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };
            foreach (var arg in context.ActionArguments)
            {
                string value = JsonConvert.SerializeObject(arg.Value, Formatting.None, jsonSetting);
                param += $"{arg.Key} : {value} \r\n";
                globalParam += value;
            }
            // 方法名
            sysActionLog.ActionName = descriptor!.ActionName;
            // 参数名 与 值
            sysActionLog.RequestParams = param;
            if (context.HttpContext.Request.Path.Equals("/api/UserLogin/Login"))
            {
                sysActionLog.ActionTime = DateTime.Now;
            }
            else
            {
                string Token = context.HttpContext.Request.Headers["Authorization"];
                // Token失效
                if (Token.IsNullOrEmpty())
                {
                    context.HttpContext.Response.StatusCode = 401;
                    sysActionLog.ResponseStatusCode = context.HttpContext.Response.StatusCode.ToString();
                }
                else
                {
                    Token = Token.Split(" ")[1];
                    var userId = App.User?.FindFirstValue("UserId");
                    Console.WriteLine(userId);
                    sysActionLog.ActionUserId = userId;
                    var username = App.User?.FindFirstValue("UserName");
                    Console.WriteLine(username);
                    sysActionLog.ActionUserName = username;
                }
                sysActionLog.ActionTime = DateTime.Now;
            }

        }

        public override void OnActionExecuted(ActionExecutedContext context)
        {
            // 获取响应状态码
            sysActionLog.ResponseStatusCode = context.HttpContext.Response.StatusCode.ToString();

            _defaultDbContext.SysActionLogs.Add(sysActionLog);
            _defaultDbContext.SaveChanges();
        }
    }
}
